<?php

/**
 * Curl post-request function
 *
 * @return string on success, http code or zero-value on failure.
 * @param string $url
 * @param array  $postData
 */
function curlPostRequest($url, $postData = array()) {

    $hdl = curl_init($url);

    curl_setopt($hdl, CURLOPT_SSLVERSION, 3);
    curl_setopt($hdl, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($hdl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($hdl, CURLOPT_TIMEOUT, 60);
    curl_setopt($hdl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($hdl, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($hdl, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($hdl, CURLOPT_HTTPHEADER, array('Connection: Close'));
    curl_setopt($hdl, CURLOPT_POST, true);
    curl_setopt($hdl, CURLOPT_POSTFIELDS, $postData);

    $response = curl_exec($hdl);

    $httpStatus = curl_getinfo($hdl, CURLINFO_HTTP_CODE);

    curl_close($hdl);

    return ($httpStatus == 200) ? $response : $httpStatus;
}

function isValidIPAddress($ip,$limit)
{

    if (empty($limit)) {
        return true;
    }
    if (!is_array($limit)) {
        $limit = array($limit);
    }
    $ip_segments = explode('.', $ip);
    $validIP = false;
    foreach($limit as $ip_rule) {
        $rule_segments = explode('.', $ip_rule);
        $i = 0;
        foreach($rule_segments as $rule_segment) {
            if ($rule_segment == '*') {
                continue;
            }
            $rule_segment = explode('-', $rule_segment);
            if (count($rule_segment) == 1) {
                if ($rule_segment[0] != $ip_segments[$i]) {
                    continue 2;
                }
            } elseif (count($rule_segment) == 2) {
                sort($rule_segment);
                if ($rule_segment[0] > $ip_segments[$i] || $rule_segment[1] < $ip_segments[$i]) {
                    continue 2;
                }
            } else {
                return false; // error in rule_segment
            }
            $i++;
        }
        $validIP = true;
    }
    return $validIP;
}
